<template>
  <div class="search-bar">
    <el-form ref="queryFormRef" :inline="true">
      <el-form-item>
        <SearchBar :show_checkbox="props.show_checkbox" @onSearch="onSearch"></SearchBar>
      </el-form-item>
    </el-form>
  </div>

  <el-card shadow="never">
    <div class="flex-x-between mb-10px">
      <div>
        <!-- 全选按钮（列表模式下显示） -->
        <el-checkbox v-if="!showGrid" v-model="isAllSelected" @change="handleSelectAll">
          全选
        </el-checkbox>
        <!-- 按钮插槽 -->
        <slot name="button"></slot>
      </div>
      <div>
        <el-button icon="Grid" circle title="表格" @click="handleGrid"></el-button>
        <el-button icon="List" circle title="列表" @click="handleList"></el-button>
      </div>
    </div>

    <!-- 表格模式 -->
    <div v-if="showGrid">
      <ArticleTable
        ref="articleTableRef"
        :listData="pageData"
        :show_checkbox="true"
        :selected="props.selected"
        :page_index="queryParams.pageNum"
        :page_size="queryParams.pageSize"
        @selection-change="handleSelectionChange"
      >
        <template #operation>
          <!-- 按钮插槽 -->
          <slot name="operation"></slot>
        </template>
      </ArticleTable>
    </div>

    <!-- 列表模式 -->
    <div v-if="!showGrid">
      <ArticleList
        ref="articleListRef"
        :listData="pageData"
        :show_checkbox="true"
        @selection-change="handleSelectionChange"
      ></ArticleList>
    </div>

    <!-- 分页 -->
    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import ArticleList from "./ArticleList.vue";
import ArticleTable from "./ArticleTable.vue";
import { ArticleQuery } from "./type";
import ArticleAPI, { ArticlePageVO, ArticlePageQuery } from "@/api/project/article";

import TopicArticleAPI, {
  TopicArticlePageVO,
  TopicArticleForm,
  TopicArticlePageQuery,
} from "@/api/project/topic-article";

const props = defineProps({
  page_index: {
    type: Number,
    default: 1,
  },
  page_size: {
    type: Number,
    default: 20,
  },
  show_checkbox: {
    type: Boolean,
    default: false,
  },
  selected: {
    //选择话题数据
    type: String,
    default: "article",
  },
  topicId: {
    //选题Id
    type: Number,
    default: null,
  },
});

const loading = ref(false);
const total = ref(0);
const showGrid = ref(true); // 是否显示表格模式
const isAllSelected = ref(false); // 是否全选

// 表格组件的引用
const articleTableRef = ref();
const articleListRef = ref();

// 查询参数
const queryParams = reactive<TopicArticlePageQuery>({
  pageNum: props.page_index,
  pageSize: props.page_size,
  topicId: props.topicId,
  selected: props.selected,

  searchWords: "",
  searchType: "0",
});

// 文章表格数据
const pageData = ref<ArticlePageVO[]>([]);
const formData = reactive<TopicArticleForm>({});
const topicId = ref(0);
// 弹窗
const dialog = reactive({
  title: "添加",
  visible: false,
});

// 选中的行数据
const selectedRows = ref<ArticlePageVO[]>([]);
// 定义 emits
const emit = defineEmits<{
  (event: "onQuery"): void;
  (event: "selection-change", selection: Array<{ id: number; [key: string]: any }>): void;
}>();
// 处理子组件传递的选中行数据
const handleSelectionChange = (selection: any) => {
  selectedRows.value = selection;
  emit("selection-change", selection); // 将选中的行数据传递给父组件
  // 更新全选状态
  isAllSelected.value = selectedRows.value.length === pageData.value.length;
};

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    // 全选
    selectedRows.value = [...pageData.value];
  } else {
    // 取消全选
    selectedRows.value = [];
  }
  // 通知子组件更新选中状态
  if (articleListRef.value) {
    articleListRef.value.setSelection(selectedRows.value);
  }
};

// 提交选中的数据
const handleSubmit = () => {
  const ids = selectedRows.value.map((row) => Number(row.id));
  if (!ids) {
    ElMessage.warning("请勾选数据");
    return;
  }

  if (ids) {
    loading.value = true;

    formData.topicId = topicId.value;
    formData.articleIds = ids;

    TopicArticleAPI.add(formData)
      .then(() => {
        ElMessage.success("新增成功");
        handleCloseDialog();
        onQuery();
      })
      .finally(() => (loading.value = false));
  }
};

// 切换表格模式
const handleGrid = () => {
  showGrid.value = true;
};

// 切换列表模式
const handleList = () => {
  showGrid.value = false;
};

// 关闭弹窗
const handleCloseDialog = () => {
  if (articleTableRef.value) {
    articleTableRef.value.clearSelection(); // 清空表格选中状态
  }
  if (articleListRef.value) {
    articleListRef.value.clearSelection(); // 清空列表选中状态
  }
  selectedRows.value = []; // 清空选中的行数据
  isAllSelected.value = false; // 重置全选状态
  dialog.visible = false;
};

// 查询文章
const onSearch = (queryAticleParams: ArticleQuery) => {
  queryParams.searchWords = queryAticleParams.searchWords;
  queryParams.searchType = queryAticleParams.searchType;
  if (props.selected === "article_topic") {
    queryParams.selected = "article_topic";
    queryParams.topicId = props.topicId;
  } else {
    if (queryAticleParams.selected) {
      queryParams.selected = "article_notin";
    } else {
      queryParams.selected = "article";
      /** 
      if (queryParams.searchWords === "") {
        ElMessage.warning("请输入检索信息");
        return;
      }
      */
    }
  }

  handleQuery();
};

/** 查询选题文章 */
function handleQuery() {
  loading.value = true;

  TopicArticleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

const onQuery = () => {
  emit("onQuery");
};

/** 处方查询 */
let articleId = ref(0);
let articleTitle = ref("");
const articleTcmRef = ref();
function handleTcmQuery(id: number, title: string) {
  articleId.value = id;
  articleTitle.value = title;
}

/** 删除选题文章 */
function handleDelete(id?: number) {
  const ids = [id || selectedRows.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      TopicArticleAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          // handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

// 打开弹窗
const openShowDialog = async (id: string, title: string) => {
  dialog.visible = true;
  dialog.title = "添加" + title;
  topicId.value = Number(id);
};

defineExpose({
  openShowDialog,
  handleQuery,
});

onMounted(() => {
  console.log("ArticleTemplate mounted");
});
</script>
